<template>
  <view class="container">
    <!-- 头像加名字 -->
    <view class="head">
      <image 
        @click="changeAvatar" 
        class="avatar" 
        :src="imagePath" 
        mode="aspectFill"
      />
      <text class="username">{{ userInfo.name || '未设置' }}</text>
    </view>
    
    <!-- 具体的个人信息,编辑状态的时候可以修改 -->
    <view class="Info-card">
      <view 
        class="Info-item" 
        v-for="(value, key) in userInfo" 
        :key="key" 
        @click="setnewvalue(key)"
      >
        <text class="item-title">{{ fieldLabels[key] }}</text>
        <text class="item-content" v-if="key !== 'gender' && key !== 'department'">
          {{ value || '未设置' }}
        </text>
        <view class="item-content" v-else>
          <picker 
            :disabled="!edit"
            @change="(e) => handlePickerChange(key, e)"
            :value="getPickerIndex(key)"
            :range="key === 'gender' ? genderOptions : departmentOptions"
          >
            {{ userInfo[key] || '请选择' }}
          </picker>
        </view>
        <text class="cuIcon cuIcon-edit" v-if="edit && key !== 'id'"></text>
      </view>
    </view>
    
    <!-- 编辑按钮 -->
    <wButton
      class="edit"
      :text="edit ? '保存' : '编辑'"
      @click="changeedit"
      :bgColor="edit ? '#52C41A' : '#1890FF'"
    ></wButton>
    
    <!-- 退出登录按钮 -->
    <wButton
      class="logout-btn"
      text="退出登录"
      @click="handleLogout"
      bgColor="#FF4D4F"
    ></wButton>
    
    <!-- 弹出层 -->
    <popup 
      :show="show && currentKey !== 'gender' && currentKey !== 'college'" 
      @close="closepopup" 
      @confirm="confirmnewvalue" 
      :title="title"
    >
      <input 
        class="inputnewInfo" 
        type="text" 
        v-model="newvalue"
        placeholder="请输入新内容"
      />
    </popup>
    
    <!-- 底部导航栏 -->
    <view class="tab-bar">
      <view 
        class="tab-item" 
        :class="{active: currentTab === 0}" 
        @click="switchTab(0)"
      >
        <text class="cuIcon cuIcon-home"></text>
        <text class="tab-text">首页</text> 
      </view>
      
      <view 
        class="tab-item" 
        :class="{active: currentTab === 1}" 
        @click="switchTab(1)"
      >
        <text class="cuIcon cuIcon-form"></text>
        <text class="tab-text">申请</text>
      </view>
      
      <view 
        class="tab-item" 
        :class="{active: currentTab === 2}" 
        @click="switchTab(2)"
      >
        <text class="cuIcon cuIcon-message"></text>
        <text class="tab-text">消息</text>
      </view>
      
      <view 
        class="tab-item" 
        :class="{active: currentTab === 3}" 
        @click="switchTab(3)"
      >
        <text class="cuIcon cuIcon-my"></text>
        <text class="tab-text">我的</text>
      </view>
    </view>
  </view>
</template>
<script>
import popup from '@/components/popup/popup.vue'
import wButton from '@/components/watch-login/watch-button.vue'

export default {
  components: { popup, wButton },
  data() {
    return {
      userType: 0, // 默认为学生
      userInfo: {
        id: "",
        name: "",
        gender: "",
        age: "",
        address: "",
        phoneNumber: "",
        email: "",
        signature: "",
        contact: "",
        department: ""
      },
      fieldLabels: {},
      currentTab: 3,
      imagePath: require('@/static/images/avatar.png'),
      edit: false,
      show: false,
      newvalue: '',
      title: '',
      backup: {},
      genderOptions: ['女', '男'],
      departmentOptions: ['电子信息学院','机电工程学院','计算机学院','材料与食品学院','人文社会科学学院','管理学院','经贸学院','外国语学院','艺术设计学院','马克思主义学院'],
      currentKey: ''
    }
  },
  onLoad() {
    // 确保 userType 被正确初始化
    const userInfo = uni.getStorageSync('userInfo');
    if (userInfo) {
      this.userType = userInfo.type || 0; // 默认为学生
    }
    
    uni.$on('updateUserType', (res) => {
      this.userType = res.type;
      this.initDynamicConfig();
      this.initFromLocalStorage();
    });
    this.initDynamicConfig();
  },
  onShow() {
    uni.setStorageSync('userAuth', true);
    const userAuth = uni.getStorageSync('userAuth');
    if (!userAuth) {
      uni.redirectTo({ url: '/pages/login/login' });
      return;
    }
    this.currentTab = 3;

    this.initFromLocalStorage();
  },
  methods: {
    initDynamicConfig() {
      const isStudent = this.userType === 0;
      const isTeacher = this.userType === 2;

      this.fieldLabels = {
        id: isStudent ? '学号' : '工号',
        name: '姓名',
        gender: '性别',
        age: '年龄',
        address: '地址',
        phoneNumber: '电话号码',
        email: '邮箱',
        signature: isStudent ? '个性签名' : '教学宣言',
        contact: isStudent ? '家长电话' : '办公电话',
        department: isStudent ? '所属院系' : '所属学院'
      };
    },
    initFromLocalStorage() {
      const storedUser = uni.getStorageSync('userInfo') || {};
      if (this.userType === 2) {
        storedUser.roleName = 'teacher';
      } else if (this.userType === 0) {
        storedUser.roleName = 'student';
      }

      this.userInfo = {
        id: storedUser.id || '',
        name: storedUser.name || '',
        gender: storedUser.gender === 1 ? '男' : '女' || '',
        age: storedUser.age || '',
        address: storedUser.address || '',
        phoneNumber: storedUser.phoneNumber || '',
        email: storedUser.email || '',
        signature: storedUser.signature || '',
        contact: storedUser.contact || '',
        department: storedUser.department || ''
      };

      if (storedUser.avatar) {
        this.imagePath = storedUser.avatar;
      }
    },
    handleLogout() {
      uni.showModal({
        title: '提示',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            uni.removeStorageSync('userInfo');
            uni.removeStorageSync('userAuth');
            uni.reLaunch({ url: '/pages/login/login' });
            uni.showToast({ title: '已退出登录', icon: 'none' });
          }
        }
      });
    },
    switchTab(index) {
      this.currentTab = index;
      
      // 动态生成路由表
      const routes = [
        this.userType === 2 ? '/pages/teacher/teacher' : '/pages/student/student',
        '/pages/application/list',
        '/pages/notification/list',
        '/pages/user/profile'
      ];
      
      // 添加跳转保护
      if (index >= routes.length) {
        uni.showToast({
          title: '功能正在开发中',
          icon: 'none'
        });
        return;
      }
      
      uni.navigateTo({
            url: routes[index],
            success: () => {
              console.log('路由跳转成功:', routes[index]);
            },
            fail: (err) => {
              console.error('路由跳转失败:', err);
              uni.showToast({
                title: '页面加载失败',
                icon: 'none'
              });
            }
          });
    },
			
			//修改老师的个人信息
			 async saveUserInfo() {
			       try {
			         // 更新本地存储数据
			         const updatedInfo = {
			           ...uni.getStorageSync('userInfo'),
			           ...this.userInfo,
			           gender: this.userInfo.gender === '男' ? 1 : 0
			         };
			         
			         uni.setStorageSync('userInfo', updatedInfo);
			         
			         uni.showToast({
			           title: '信息更新成功',
			           icon: 'success'
			         });
			       } catch(error) {
			        this.userInfo = {...this.backup}
			        uni.showToast({
			          title: error.message || '保存失败',
			          icon: 'none'
			        })
			      } finally {
			        uni.hideLoading()
			      }
			    },
			// 构建保存参数
			    buildSaveParams() {
			      const baseParams = {
			        ...this.userInfo,
			        gender: this.userInfo.gender === '男' ? 1 : 0
			      }
			
			      // 处理字段差异
			      if (this.userType === 0) {
			        return {
			          ...baseParams,
			          college: baseParams.department
			        }
			      }
			      return {
			        ...baseParams,
			        department: baseParams.department
			      }
			    },
			//更换头像
			 async changeAvatar() {
			      uni.chooseImage({
			        count: 1,
			        success: async (res) => {
			          try {
			            const api = await this.getCurrentApi()
			            const file = res.tempFiles[0]
			            
			            uni.showLoading({ title: '上传中...' })
			            const res = await api.updateAvatar({
			              id: this.userInfo.id,
			              avatar: file.path
			            })
			            
			            this.imagePath = file.path
			            uni.setStorageSync('userAvatar', file.path)
			            uni.showToast({ title: '头像更新成功' })
			          } catch(error) {
			            uni.showToast({
			              title: error.message || '上传失败',
			              icon: 'none'
			            })
			          } finally {
			            uni.hideLoading()
			          }
			        }
			      })
			    },
			
			//切换编辑状态
			changeedit(){
				if(!this.edit)
				this.backup={...this.userInfo}
				//保存的时候调用接口
				if(this.edit){
					this.saveUserInfo({
						...this.userInfo,
						gender: this.userInfo.gender  === '男' ? 1 : 0
					})
					console.log(this.userInfo)
				}
				this.edit=!this.edit
			},
			
			//修改个人的信息
			setnewvalue(key) {
			  if (!this.edit || key === 'gender' || key === 'department' || key === 'id') return;
			  this.title = `修改${this.fieldLabels[key]}`;
			  this.newvalue = `${this.userInfo[key]}`;
			  this.currentKey = key; // 修复拼写错误
			  this.show = true;
			},
			
			//校验修改的信息
			// 修改后的校验方法
			validateInput(value, currentkey) {
			  // 空值校验
			  if (!value || value.trim() === '') {
			    return '输入内容不能为空';
			  }
			  
			  switch (currentkey) {
			    case 'phoneNumber':
			      return /^1[3-9]\d{9}$/.test(value) ? true : '请输入正确的手机号码';
			    case 'contact': // 家长电话或办公电话
			      return /^1[3-9]\d{9}$/.test(value) ? true : '请输入正确的电话号码';
			    case 'email':
			      return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value) ? true : '请输入正确的邮箱格式';
			    case 'name':
			      return value.trim().length >= 2 ? true : '姓名至少2个字符';
			    case 'signature':
			      return value.trim().length <= 14 ? true : '个性签名不能多于14个字';
			    case 'age':
			      return /^\d+$/.test(value) && value > 0 && value < 120 ? true : '请输入有效的年龄';
			    default:
			      return true; // 默认通过校验
			  }
			},
			
			// 修改后的确认方法
			confirmnewvalue() {
			  // 去除前后空格
			  this.newvalue = this.newvalue.trim();
			  
			  const validateresult = this.validateInput(this.newvalue, this.currentKey);
			  if (validateresult !== true) {
			    uni.showToast({
			      title: validateresult,
			      icon: 'none',
			      duration: 2000
			    });
			    return;
			  }
			  
			  // 校验通过才更新数据
			  this.userInfo[this.currentKey] = this.newvalue;
			  this.closepopup();
			},
			
			closepopup(){
				this.show=false
				this.newvalue=''
			},
			
			//当前选中的性别和学院	
			getPickerIndex(key) {
			    if (key === 'gender') {
			      return this.genderOptions.indexOf(this.userInfo.gender)
			    } else if (key === 'department') {
			      return this.departmentOptions.indexOf(this.userInfo.department)
			    }
			    return 0
			  },
			  
			handlePickerChange(key, e) {
			    const value = e.detail.value
			    if (key === 'gender') {
			      this.userInfo.gender = this.genderOptions[value]
			    } else if (key === 'department') {
			      this.userInfo.department = this.departmentOptions[value]
			    }
			  }
		}
	}
</script>

	<style>
	@import url('./css/profile.css');
	@import url("../../components/watch-login/css/icon.css");
</style>
